package com.tizona.system;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.sql.*;
import java.util.*;

import com.tizona.TarifdConfig;
import com.tizona.service.ContractManager;


public class Tarifd
{
    java.util.Date last_time;
    TarifdConfig cfg;

    protected final Log logger = LogFactory.getLog(getClass());

    ResultSet nalc_res; // nonactive LCs for ProcessAllLC

    int processing_day = -1;
    Calendar processingAllContract = Calendar.getInstance();
    boolean process_all_flag = false;

    boolean need_stopsession = false;
    boolean need_mailhup     = false;
    boolean need_hostinghup  = false;
    boolean need_newshup     = false;
    boolean need_subhup      = false;

    HashMap se_maxtimestamps = new HashMap(1000);

    Hashtable all_tp;

    protected ContractManager contractMng;

    public Tarifd() {
    }

    public Tarifd(TarifdConfig cfg_)  {

        cfg=cfg_;
        last_time=new java.util.Date();     //current date and time

        contractMng = cfg.contractMan;

    }


    private void clearEvents()  {
        need_stopsession = false;
        need_mailhup     = false;
        need_hostinghup  = false;
        need_newshup     = false;
        need_subhup      = false;
    }

    private void raiseEvent(String eventName)  {
        Event.raise(eventName);
        logger.debug("Event "+eventName+" generated");
    }

    void raiseEvents() {
        if(need_stopsession) raiseEvent("STOPSESSION");
        if(need_subhup)      raiseEvent("SUBHUP");
        if(need_mailhup)     raiseEvent("MAILHUP");
        if(need_hostinghup)  raiseEvent("HOSTINGHUP");
        if(need_newshup)     raiseEvent("NEWSHUP");
        clearEvents();
    }

    public static void main(String args[]) throws Exception {

        Tarifd inst = new Tarifd(new TarifdConfig(args));

        System.exit(inst.process() ? 0 : -1);
    }


    /**
     * Main process cycle for processing contracts
     *
     * @return
     * @throws Exception
     */
    public boolean process() throws Exception {


        //Variant 1 - run to process one LC
        if(cfg.process_one_lc>0)
        {
            return true;
        }


        last_time.setTime(last_time.getTime() - cfg.tarifd_period); //to force update

        //Variant 2 - run in infinite loop to process all LCs
        for(;;)
        {
            Calendar cur_time= Calendar.getInstance()/*, min_timestamp = getMinTimestampChunks()*/;

            if(cfg.needReadConfig())
            {
                cfg.readConfig();
                continue;
            }

            //(cur_time.get(Calendar.MINUTE) == 7) && (cur_time.get(Calendar.HOUR_OF_DAY) == 0) &&
            if((cur_time.getTimeInMillis() - last_time.getTime() >= cfg.tarifd_period))
            {
                last_time=cur_time.getTime();

                contractMng.handleActiveContracts(cur_time);

                need_stopsession = true;

                raiseEvents();
                logger.info("End Cycle");
            }

            if(!processingAllContract.after(cur_time)) {

                logger.debug("processingAllContract = "+processingAllContract.getTime()
                        + " cur_time = " + cur_time.getTime());
                contractMng.handleAllContracts(cur_time);
                processingAllContract = (Calendar) cur_time.clone();
                processingAllContract.add(Calendar.DAY_OF_MONTH,1);

            }
            Thread.sleep(200);
        }
    }

}
